package com.dmg.flowabledemo.controller;


import liquibase.pro.packaged.A;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.engine.repository.Deployment;
import org.flowable.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;

/**
 * 流程定义控制层
 */
@RestController
public class ProcessDefinitionController {



    @Autowired
    protected RepositoryService repositoryService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private TaskService taskService;

    /**
     * 部署流程
     * @param file
     * @return
     */
    @PostMapping(value = "/deploy")
    public String deploy(@RequestParam("file") MultipartFile file) {
        try {
            Deployment deployment = repositoryService.createDeployment()
                    .addInputStream(file.getOriginalFilename(), file.getInputStream())
                    .deploy();
            return deployment.getId();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "ok";
    }

    /**
     * 启动流程实例,返回流程实例id
     * @param processDefinitionKey 流程定义key
     */
    @PostMapping(value = "/startProcessInstance")
    public String startProcessInstance(@RequestParam("processDefinitionKey") String processDefinitionKey){
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processDefinitionKey);
        if(processInstance==null){
            throw new RuntimeException("启动流程实例失败");
        }
        //返回流程实例id
        return processInstance.getId();
    }

    /**
     * 根据任务id 完成任务
     */
    @PostMapping(value = "/complete")
    public void complete(@RequestParam("taskId") String taskId){
        //完成任务
        taskService.complete(taskId);
    }

}
